package generator

import (
	"fmt"
	"os"
	"sql2entity/parser"
	"sql2entity/tmpl"
	"sql2entity/util"
	"text/template"
)

// sqlType2JavaType MySQL中类型和Java中类型对应关系
var sqlType2JavaType = map[string]string{
	"tinyint":    "Integer",
	"smallint":   "Integer",
	"mediumint":  "Integer",
	"int":        "Integer",
	"integer":    "Integer",
	"bigint":     "Long",
	"float":      "BigDecimal",
	"double":     "BigDecimal",
	"decimal":    "BigDecimal",
	"date":       "Date",
	"time":       "Date",
	"year":       "Date",
	"datetime":   "Date",
	"timestamp":  "Date",
	"char":       "String",
	"varchar":    "String",
	"tinyblob":   "byte[]",
	"tinytext":   "String",
	"blob":       "byte[]",
	"text":       "String",
	"mediumblob": "byte[]",
	"mediumtext": "String",
	"longblob":   "byte[]",
	"longtext":   "String",
}

// GetJavaType 根据MySQL中类型，得到Java中对应的类型
func GetJavaType(key string) string {
	return sqlType2JavaType[key]
}

// GenerateJavaCode 生成Java语言代码
func GenerateJavaCode(sql, tmplText string, outPath string) error {
	tableInfo := parser.GetTableInfoFromSql(sql)
	goTmpl := template.New("javaEntity").Funcs(template.FuncMap{
		"Underline2CamelCase":    util.Underline2CamelCase,
		"Underline2BigCamelCase": util.Underline2BigCamelCase,
		"GetJavaType":            GetJavaType,
	})
	if tmplText != "" {
		goTmpl = template.Must(goTmpl.Parse(tmplText))
	} else {
		goTmpl = template.Must(goTmpl.Parse(tmpl.JavaEntityTmpl))
	}
	fp, err := os.OpenFile(fmt.Sprintf("%s/%s.java", outPath, tableInfo.TableName), os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	err = goTmpl.Execute(fp, tableInfo)
	if err != nil {
		return err
	}
	return nil
}
